package com.alpha.servlets;

import java.io.IOException;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.TreeSet;

import javax.naming.NamingException;
import javax.servlet.RequestDispatcher;
import javax.servlet.ServletException;
import javax.servlet.annotation.HttpConstraint;
import javax.servlet.annotation.ServletSecurity;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import org.apache.log4j.Logger;

import com.alpha.bom.Answer;
import com.alpha.bom.Professor;
import com.alpha.bom.Question;
import com.alpha.dao.QuestionDao;

/**
 * Servlet implementation class QuestionsAdminServlet
 */
@WebServlet("/QuestionsAdminServlet")
@ServletSecurity(@HttpConstraint(rolesAllowed = {"admin"}))
public class QuestionsAdminServlet extends HttpServlet {
	private static final long serialVersionUID = 1L;
	
	private static Logger logger = Logger.getLogger(QuestionsAdminServlet.class.getName());
       
    /**
     * @see HttpServlet#HttpServlet()
     */
    public QuestionsAdminServlet() {
        super();
        // TODO Auto-generated constructor stub
    }

	/**
	 * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response)
	 */
	protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		
		logger.info(this.getClass().getSimpleName()+" get method started.");
		
		Professor professor = null;
		TreeSet<Question> questions = new TreeSet<Question>();
		String message = null;
		String success = null;
		String error = null;
		
		if(request.getParameter("success")!=null){
			success = request.getParameter("success");
		} else if(request.getParameter("error")!=null){
			error = request.getParameter("error");
		} else if(request.getParameter("message")!=null){
			message = request.getParameter("message");
		}
		
		HttpSession session = request.getSession();
		
		String category = "all";
		String type = "all";
		
		if(session.getAttribute("user")!=null){
			professor = (Professor) session.getAttribute("user");
			
			if(request.getParameter("filterCategories")!=null&&!request.getParameter("filterCategories").equals("")){
				category = request.getParameter("filterCategories");
			}
			
			if(request.getParameter("type")!=null&&!request.getParameter("type").equals("")){
				type = request.getParameter("type");
			}
			
			QuestionDao qDao = new QuestionDao();
			
			try {
				for(Question question: qDao.retrieveAllQuestions()){
					if("all".equalsIgnoreCase(category)){
						if("all".equalsIgnoreCase(type)){
							questions.add(question);
						}else{
							if(type.equalsIgnoreCase(question.getQuestionType())){
									questions.add(question);
							}
						}
					}else{
						if(category.equalsIgnoreCase(question.getCategory())){
							if("all".equalsIgnoreCase(type)){
								questions.add(question);
							}else{
								if(type.equalsIgnoreCase(question.getQuestionType())){
										questions.add(question);
								}
							}
						}
					}
				}
			} catch (NamingException e1) {
				logger.error(e1.getMessage());
				return;
			} catch (SQLException e1) {
				logger.error(e1.getMessage());
				return;
			}
			
			if(questions!=null){
				request.setAttribute("questions", questions);
			}
			if(error!=null){
				RequestDispatcher dis=request.getRequestDispatcher("QuestionsAdmin.jsp?error="+error);
	            dis.forward(request, response);
			} else if(success!=null){
				RequestDispatcher dis=request.getRequestDispatcher("QuestionsAdmin.jsp?success="+success);
	            dis.forward(request, response);
			} else if(message!=null){
				RequestDispatcher dis=request.getRequestDispatcher("QuestionsAdmin.jsp?message="+message);
	            dis.forward(request, response);
			} else {
				RequestDispatcher dis=request.getRequestDispatcher("QuestionsAdmin.jsp");
	            dis.forward(request, response);
			}
			return;
		}else{
			response.sendRedirect("Login.jsp");
			return;
		}
	}

	/**
	 * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)
	 */
	protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		
		logger.info(this.getClass().getSimpleName()+" post method started.");
				
		Professor professor = null;
		String type = "";
		String questionText = "";
		String category = "";
		String message = null;
		String success = null;
		String error = null;
		
		if(request.getParameter("success")!=null){
			success = request.getParameter("success");
		} else if(request.getParameter("error")!=null){
			error = request.getParameter("error");
		} else if(request.getParameter("message")!=null){
			message = request.getParameter("message");
		}
		
		HttpSession session = request.getSession();
		if(session.getAttribute("user") != null && session.getAttribute("user") instanceof Professor) {
			professor = (Professor) session.getAttribute("user");
		} else {
			response.sendRedirect("Login.jsp");
		}
		
		if(request.getParameter("type") != null) {
			type = request.getParameter("type");
		}
		
		if(request.getParameter("question_text") != null) {
			questionText = request.getParameter("question_text");
		}
		
		if(request.getParameter("category_name") != null) {
			category = request.getParameter("category_name");
		}
		
		int correct = Integer.parseInt(request.getParameter("answer"));
		ArrayList<Answer> choices = new ArrayList<Answer>();
		
		if(request.getParameter("type").equals("MultipleChoice")) {
			int i = 0;
			for(; request.getParameter("choice"+i) != null; i++) {
				choices.add(new Answer(request.getParameter("choice"+i)));
			}
		} else {
			choices.add(new Answer("true"));
			choices.add(new Answer("false"));
		}
		
		Question question = new Question(0, type, questionText, choices.get(correct), category);
		question.setChoices(choices);
		
		QuestionDao qDao = new QuestionDao();
		try {
			if(qDao.insertQuestion(question)) {
				if(error!=null){
					response.sendRedirect("QuestionsAdminServlet?error="+error);
				} else if(success!=null){
					response.sendRedirect("QuestionsAdminServlet?success="+success);
				} else if(message!=null){
					response.sendRedirect("QuestionsAdminServlet?message="+message);
				} else {
					response.sendRedirect("QuestionsAdminServlet?success=Question+added+successfully!");
				}
			} else {
				if(error!=null){
					response.sendRedirect("QuestionsAdminServlet?error="+error);
				} else if(success!=null){
					response.sendRedirect("QuestionsAdminServlet?success="+success);
				} else if(message!=null){
					response.sendRedirect("QuestionsAdminServlet?message="+message);
				} else {
					response.sendRedirect("QuestionsAdminServlet?error=Adding+question+failed.");
				}
			}
		} catch (NamingException e) {
			logger.error(e.getMessage());
			return;
		} catch (SQLException e) {
			logger.error(e.getMessage());
			return;
		}
	}

}
